package com.green.system.shiro;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Green
 * @Date: 2021/10/21/2:34
 * @Description:
 */

public class OptionsAccessControlFilter extends UserFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            setHeader(httpRequest,httpResponse);
            return true;
        }
        return super.preHandle(request, response);
    }

    /**
     * 为response设置header，实现跨域
     */
    private void setHeader(HttpServletRequest httpRequest, HttpServletResponse httpResponse){
        //跨域的header设置
        httpResponse.setHeader("Access-control-Allow-Origin",httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-control-Allow-Methods",httpRequest.getMethod());
        httpResponse.setHeader("Access-control-Allow-Credentials","true");
        httpResponse.setHeader("Access-control-Allow-Headers",httpRequest.getHeader("Access-Control-Request-Headers"));
        //防止乱码，适用于传输JSON数据
        httpResponse.setHeader("Content-Type","application/json;charset=UTF-8");
        httpResponse.setStatus(200);
    }
}
